package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 保存本地交易记录
     *
     * @param paymentType:支付类型 1301-订单 1302-充值
     * @param orderNo:         订单编号
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        Long userId = AuthContextHolder.getUserId();
        //1.根据订单编号查询本地交易记录，如果存在则返回即可
        PaymentInfo paymentInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOrderNo, orderNo)
        );
        if (paymentInfo != null) {
            return paymentInfo;
        }
        //2.构建本地交易记录
        paymentInfo = new PaymentInfo();


        //2.1 封装直接赋值属性：用户ID，支付类型、订单号、付款方式、支付状态
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //2.2 处理支付类型为:1301订单，封装交易金额跟内容
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //2.2.1 远程调用订单服务获取订单信息
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            Assert.notNull(orderInfo, "订单{}不存在", orderNo);
            //2.2.2 判断订单状态，未支付才能支付 订单状态：0901-未支付 0902-已支付 0903-已取消
            String orderStatus = orderInfo.getOrderStatus();
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(orderStatus)) {
                throw new GuiguException(500, "订单状态有误:" + orderStatus);
            }
            //2.2.3 封装交易金额跟内容
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setContent(orderInfo.getOrderTitle());
        }


        //2.3 处理支付类型为:1302充值，封装交易金额跟内容
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //2.2.1 远程调用账户服务获取充值信息
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            Assert.notNull(rechargeInfo, "充值{}不存在", orderNo);
            //2.2.2 判断充值状态，未支付才能支付 充值状态：0901-未支付 0902-已支付 0903-已取消
            String rechargeStatus = rechargeInfo.getRechargeStatus();
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeStatus)) {
                throw new GuiguException(500, "充值状态有误:" + rechargeStatus);
            }
            //2.3.3 封装交易金额跟内容
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent("充值：" + rechargeInfo.getRechargeAmount());
        }

        //2.4 TODO 其他属性，等支付成功后异步回调获取
        //paymentInfo.setOutTradeNo();
        //paymentInfo.setCallbackTime();
        //paymentInfo.setCallbackContent();

        //3.保存本地交易记录
        baseMapper.insert(paymentInfo);
        return paymentInfo;
    }

    /**
     * 支付成功后，更新交易记录
     *
     * @param transaction 微信交易对象
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void updatePaymentInfo(Transaction transaction) {
        //1.根据微信交易对象中的商户订单号查询本地交易记录 如果已支付 忽略
        String orderNo = transaction.getOutTradeNo();
        PaymentInfo paymentInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOrderNo, orderNo)
        );
        //支付状态：1401-未支付 1402-已支付
        String paymentStatus = paymentInfo.getPaymentStatus();
        if (SystemConstant.PAYMENT_STATUS_UNPAID.equals(paymentStatus)) {
            //2.更新本地交易记录状态：已支付 更新：交易编号、回调时间、回调内容
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
            paymentInfo.setOutTradeNo(transaction.getTransactionId());
            paymentInfo.setCallbackTime(new Date());
            paymentInfo.setCallbackContent(transaction.toString());
            baseMapper.updateById(paymentInfo);

            //3.处理支付类型：1301订单 订单状态更新及虚拟物品发货
            String paymentType = paymentInfo.getPaymentType();
            if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
                Result result = orderFeignClient.orderPaySuccess(orderNo);
                if (result.getCode().intValue() != 200) {
                    throw new GuiguException(result.getCode(), result.getMessage());
                }
            }
            //4.处理支付类型：1302充值 余额充值
            if(SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)){
                //4.1 远程调用账户服务，修改充值状态，完车充值业务
                Result result = accountFeignClient.rechargePaySuccess(orderNo);
                if (result.getCode().intValue() != 200) {
                    throw new GuiguException(result.getCode(), result.getMessage());
                }
            }
        }
    }
}
